package com.learn.xueer.ui.activity

import android.os.Bundle
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import com.github.mikephil.charting.components.Legend
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.data.BarData
import com.github.mikephil.charting.data.BarDataSet
import com.github.mikephil.charting.data.BarEntry
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter
import com.github.mikephil.charting.formatter.LargeValueFormatter
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayout.OnTabSelectedListener
import com.learn.xueer.R
import com.learn.xueer.app.base.BaseActivity
import com.learn.xueer.data.model.bean.MissionInfo
import com.learn.xueer.databinding.ActivityAcademicPerformanceBinding
import com.learn.xueer.ui.adapter.WorkAliAdapter
import com.learn.xueer.ui.viewmodel.MineViewModel
import kotlinx.android.synthetic.main.activity_academic_performance.mChart
import kotlinx.android.synthetic.main.activity_academic_performance.rv_al
import kotlinx.android.synthetic.main.activity_academic_performance.tab_pic
import kotlinx.android.synthetic.main.activity_academic_performance.tv1
import me.hgj.jetpackmvvm.util.startActivity


/**
 * 学习成绩
 */
class AcademicPerformanceActivity :
    BaseActivity<MineViewModel, ActivityAcademicPerformanceBinding>() {


    private val adapter: WorkAliAdapter by lazy { WorkAliAdapter(arrayListOf()) }

    inner class ProxyClick {
        fun back() {
            finish()
        }

        fun history() {
            startActivity(StudyHistoryActivity::class)
        }


    }

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.click = ProxyClick()
        mDatabind.viewmodel = mViewModel
        mViewModel.missionHistoryReq("1")
        tab_pic.addOnTabSelectedListener(object : OnTabSelectedListener {
            override fun onTabSelected(p0: TabLayout.Tab?) {
                mViewModel.missionHistoryReq(p0?.position.toString())
            }

            override fun onTabUnselected(p0: TabLayout.Tab?) {

            }

            override fun onTabReselected(p0: TabLayout.Tab?) {

            }

        })
        initBarChart()
    }

    private fun initBarChart() {
        mChart.description.isEnabled = false
        mChart.setPinchZoom(false)
        mChart.setDrawBarShadow(false)
        mChart.isScaleXEnabled = true
        mChart.isScaleYEnabled = false
        mChart.setDrawGridBackground(false)
        val l = mChart.legend
        l.verticalAlignment = Legend.LegendVerticalAlignment.TOP

        l.horizontalAlignment = Legend.LegendHorizontalAlignment.LEFT

        l.orientation = Legend.LegendOrientation.HORIZONTAL
        l.setDrawInside(false)
        l.yOffset = 0f
        l.yEntrySpace = 0f
        l.textSize = 8f
        l.form = Legend.LegendForm.LINE

        val xAxis = mChart.xAxis
        xAxis.granularity = 1f
        xAxis.setDrawGridLines(false)
        xAxis.position = XAxis.XAxisPosition.BOTTOM
        xAxis.setCenterAxisLabels(true)
        xAxis.setAvoidFirstLastClipping(true)

        val leftAxis = mChart.axisLeft
        leftAxis.valueFormatter = LargeValueFormatter()
        leftAxis.setDrawGridLines(false)
        leftAxis.spaceTop = 35f
        leftAxis.axisMinimum = 0f // this replaces setStartAtZero(true)
        mChart.axisRight.isEnabled = false //不使用右侧Y轴

        xAxis.axisMinimum = 0f
        //保证Y轴从0开始，不然会上移一点
        leftAxis.axisMinimum = 0f
    }

    override fun createObserver() {
        mViewModel.missionHistoryResponse.observe(this, Observer {
            tv1.text =
                "作业完成率：${it.mission_done_lv}%（对比上个周期${it.mission_done_lv_last}%）\n作业得分率：${it.mission_get_score_lv}%（对比上个周期${it.mission_get_score_lv_last}%"


            setData(it.date_list, it.class_score_list, it.self_score_list)

            var list = ArrayList<MissionInfo>()
            list.add(MissionInfo(0.0, 0.0, 1, 0.0, 0.0, "明细"))
            list.addAll(it.mission_info)
            rv_al.adapter = adapter
            rv_al.layoutManager = GridLayoutManager(this, list.size)
            adapter.setList(list)
        })
    }

    private fun setData(
        mLabels: List<String>,
        classScoreList: List<Double>,
        selfScoreList: List<Double>
    ) {
        //设置柱子宽度
//关键的地方在于 需要满足该等式,标签才能居中：
//(barSpace + barWidth) * 柱形图数量(比如我的是每组两个) + groupSpace = 1
        //0.1+0.1 0.3
        val groupSpace = 0.4f
        val barSpace = 0.15f
        val barWidth = 0.15f

        // 对X轴格式的设置
        mChart.xAxis.valueFormatter = IndexAxisValueFormatter(mLabels)
        mChart.xAxis.labelCount = mLabels.size
        val selfBarData = ArrayList<BarEntry>()
        val classBarData = ArrayList<BarEntry>()

        for (i in selfScoreList.indices) {
            selfBarData.add(BarEntry(i.toFloat(), selfScoreList[i].toFloat()))
        }

        for (i in classScoreList.indices) {
            classBarData.add(BarEntry(i.toFloat(), classScoreList[i].toFloat()))
        }

        val set1: BarDataSet
        val set2: BarDataSet
        if (mChart.data != null && mChart.data.dataSetCount > 0) {
            set1 = mChart.data.getDataSetByIndex(0) as BarDataSet
            set2 = mChart.data.getDataSetByIndex(1) as BarDataSet
            set1.values = selfBarData //A公司的所有年份数据
            set2.values = classBarData
            mChart.data.notifyDataChanged()
            mChart.notifyDataSetChanged()
        } else {
            // create 4 DataSets
            set1 = BarDataSet(selfBarData, "我的成绩")
            set1.color = resources?.getColor(R.color._0cb76c)!!
            set2 = BarDataSet(classBarData, "班级平均成绩")
            set2.color = resources?.getColor(R.color.ff9917)!!

            val data = BarData(set1, set2) //,set4
            mChart.data = data
        }

        //设置柱状图的宽度及字体大小等等
        mChart.barData.barWidth = barWidth
        mChart.barData.setValueTextSize(7f)

        mChart.groupBars(0f, groupSpace, barSpace)
        mChart.invalidate() //刷新图表
    }
}